package com.mq.produce.simple.v2;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

/**
 * @Classname CustomerProduce
 * @Description 生产者幂等性和事务
 * @Version 1.0.0
 * @Date 2025/3/7 9:53
 * @Created by ncs
 */
public class CustomerProduceTranactions {

    static String kafkaServer = "192.168.125.100:9093,192.168.125.100:9094,192.168.125.100:9095";

    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaServer);
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        //指定事务id 事务是基于生产者消息幂等  默认是开启状态
        properties.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "first-topic-1");
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);
        //1. 初始化事务 目的是从broker的主题__transaction_state拿到对应事务的状态
        kafkaProducer.initTransactions();
        //2. 开始事务 继续事务，如果之前对应的事务id未完成 那么继续 否则就开启一个新的事务
        kafkaProducer.beginTransaction();
        try {
            //3. 发送消息
            for (int i = 0; i < 5; i++) {
                ProducerRecord<String, String> producerRecord = new ProducerRecord<>("first-topic", "first-message" + i);
                kafkaProducer.send(producerRecord);
            }
            int i = 1/0;
            //4. 提交事务
            kafkaProducer.commitTransaction();
        }catch (Exception e) {
            e.printStackTrace();
            //5. 回滚事务
            kafkaProducer.abortTransaction();
        }finally {
            kafkaProducer.close();
        }
    }
}
